package common.servlet;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import product.jbpmDesign.JbpmDesignService;

public class JbpmDesign extends HttpServlet {
	private JbpmDesignService jbpmDesignService = new JbpmDesignService(); 
	public JbpmDesign() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String xml = request.getParameter("xml");
		String key = request.getParameter("key");
		Writer writer = null;
		out("key="+key);
		out("xml="+xml);
		String xmlFilePath = "E:/workspace/istudy/resource/xml/"+key+".xml";
		String pngFilePath = "E:/workspace/istudy/resource/img/"+key+".png";
		File xmlFile = new File(xmlFilePath);
		File pngFile = new File(pngFilePath);
		//xml
		jbpmDesignService.saveXml(xmlFile, xml);
		//png
		jbpmDesignService.buildPngFromXml(xmlFile,pngFile);
		//
		response.setContentType("text/html; charset=UTF-8");
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map stateMap = new HashMap();
		stateMap.put("state", "success");
		JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( stateMap );
		jsonObject.write(writer);
	}

	public void init() throws ServletException {
		
	}
	private void out(Object object){
		System.out.println(object);
	}
}
